<template>
  <Navbar title="注册" left-text="返回" left-arrow />

  <van-form style="margin-top: 40px">
    <van-cell-group inset>
      <van-field
        v-model="state.tel"
        name="tel"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model.trim="state.sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :disabled="state.tel.length !== 11 || num !== 0"
            @click="send"
          >
            发送验证码{{ num ? "(" + num + ")" : null }}
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        :disabled="state.tel.length !== 11 || state.sms.length !== 5"
        round
        block
        type="danger"
        @click="submit"
      >
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import Navbar from "@/components/Navbar.vue";
import { reactive, ref } from "vue";
import { regiterApi, sendCodeApi, checkCodeApi } from "@/api/user";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";

const state = reactive({
  tel: "",
  sms: "",
});
const num = ref<number>(0);

const send = async () => {
  const res = await regiterApi({
    tel: state.tel,
  });
  if (res) {
    const res2 = await sendCodeApi({
      tel: state.tel,
    });
    if (res2) {
      showToast(res2.data);
      num.value = 10;
      let timer = setInterval(() => {
        num.value--;
        if (num.value === 0) {
          clearInterval(timer);
        }
      }, 1000);
    }
  }
};

const router = useRouter();
const store = useUserStore();
const submit = async () => {
  const res = await checkCodeApi({
    tel: state.tel,
    telcode: state.sms,
  });
  if (res) {
    // 手机号需要在下一个页面用，可以存本地存储
    // localStorage.setItem("tel", state.tel);

    // 也可以使用路由来做页面的传参
    // router.push("/psw/" + state.tel);

    // 也可以将手机号存到仓库pinia了
    store.tel = state.tel;
    router.push("/psw");
  }
};
</script>
